package com.woniu.orderservice.controller;
import com.woniu.orderservice.client.GoodsServiceClient;
import com.woniu.orderservice.client.UserServiceClient;
import com.woniu.orderservice.entity.Goods;
import com.woniu.orderservice.entity.Orderinfos;
import com.woniu.orderservice.entity.Orders;
import com.woniu.orderservice.entity.ResultBody;
import com.woniu.orderservice.service.OrderinfosService;
import com.woniu.orderservice.service.OrdersService;
import com.woniu.orderservice.util.OrdersStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


@RestController
@RequestMapping("orders")
public class OrdersController {

    @Resource
    private OrdersService ordersService;

    @Autowired
    private OrderinfosService orderinfosService;

    @Autowired
    GoodsServiceClient goodsServiceClient;

    @Autowired
    UserServiceClient userServiceClient;

    @RequestMapping("/detail")
    public ModelAndView detail(String orderNo, ModelAndView modelAndView) {
        Orders orders = ordersService.findOrderByOrderNo(orderNo);
        List<Orderinfos> infos = ordersService.findOrderItems(orders.getId());
        modelAndView.addObject("orders", orders);
        modelAndView.addObject("infos", infos);
        modelAndView.setViewName("oders");//跳转到订单页面，显示当前订单中的信息及明细
        return modelAndView;
    }
    @Transactional
    @GetMapping("/createOrder")
    public ResultBody createOrder(Integer goodsId, Integer goodsCount, HttpServletRequest request) throws SQLException {
        //查询商品信息
        Goods goods = goodsServiceClient.selectOne(goodsId);
        //判断是否为拍卖品，确定商品价格
        if(goods.getIsauction()==1){
            //拍卖品通过拍卖成交价获取价格
            userServiceClient.findByGoodsId(goods.getId()).getResult();
        }
        //进行库存校验
        if (goods.getGoodscount()==0||goods.getGoodscount()==null||goods.getGoodscount()<goodsCount){
            return ResultBody.error("库存不足");
        }
        //生成15位订单号
        String onumber = new Date().getTime() + "" + (int) Math.random() * 10 + (int) Math.random() * 10;
        //获取用户信息
        int userId = (int)request.getSession().getAttribute("userId");
        //创建订单对象
        Orders order = new Orders();
        //订单创建时间
        order.setCreatetime(new Date());
        order.setStatus(OrdersStatus.WAITFORPAY.getI());
        order.setUpdatetime(new Date());
        order.setOrdernumber(onumber);
        order.setUserid(userId);
        try {
            //向数据库插入订单信息
            ordersService.insert(order);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        //生成订单明细信息
        Orderinfos orderinfos=new Orderinfos();
        orderinfos.setGoodsid(goodsId);
        orderinfos.setGoodsnumber(goodsCount);
        orderinfos.setGoodsprice(goods.getGoodsprice()*goodsCount);
        orderinfos.setOrderid(order.getId());
        //插入订单明细信息
        try {
            orderinfosService.insert(orderinfos);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return ResultBody.success(onumber);
    }

    //根据订单id获取订单信息
    @RequestMapping("/getOrder")
    @ResponseBody
    public ResultBody getOrder(Integer id) {
        Orders orders = ordersService.queryAllById(id);
        return ResultBody.success(orders);
    }


    //查询该用户所有订单
    @RequestMapping("/getOrders")
    @ResponseBody
    public ResultBody getOrders(Integer userId) {
        List<Orders> orders= null;
        try {
            orders = ordersService.queryByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return  ResultBody.success(orders);
    }
    //查询该用户所有订单明细带商品信息
    @RequestMapping("/list")
    @ResponseBody
    public ResultBody list(Integer userId) {
        List<Orders> orders= null;
        try {
            //查询订单及订单明细信息
            orders = ordersService.queryAllByUserId(userId);
            //查询订单商品信息
            Iterator<Orders> iterator = orders.iterator();
            while (iterator.hasNext()){
                Orders next = iterator.next();
                Integer goodsid = next.getOrderinfos().getGoodsid();
                Goods goods = goodsServiceClient.selectOne(goodsid);
                next.getOrderinfos().setGoods(goods);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return  ResultBody.success(orders);
    }
}